package com.crealth.handler;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.crealth.ConstantDefine;
import com.crealth.db.TeamWorkDiaryDb;
import com.crealth.memcached.UserCached;
import com.crealth.model.TeamWorkDiaryModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;

public class TeamWorkDiaryHandler {
	private static Logger errorLog = Logger.getLogger("error_log");

	public static NetMessageData saveWorkDiary(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject msgJson = revData.getRevDataMsgJson();
		JSONObject resJson = new JSONObject();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() != ConstantDefine.Team_Manager) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}		
		int teamID = user.getTeamID();
		if (teamID <= 0) {
			errorLog.error("userID: " + userID + "  teamID is 0");
			return null;
		}
		TeamWorkDiaryModel workDiary = new TeamWorkDiaryModel();
		Date curDate = new Date(System.currentTimeMillis());
    	String strtoday = new SimpleDateFormat("yyyyMMdd").format(curDate);
		workDiary.parseFromJson(msgJson);
		workDiary.setUserID(userID);
		workDiary.setTeamID(teamID);
		workDiary.setWorkDay(strtoday);
		TeamWorkDiaryModel existDiary = null;
		if (workDiary.getId() > 0) {
			TeamWorkDiaryDb.updateTeamWorkDiaryByID(workDiary);
		}
		else {
			existDiary = TeamWorkDiaryDb.selectTeamWorkDiary(teamID, strtoday);
			if (existDiary != null) {
				TeamWorkDiaryDb.updateTeamWorkDiaryByID(workDiary);
			} else {
				TeamWorkDiaryDb.insertTeamWorkDiary(workDiary);
			}
		}
		
		resJson.put("resCode", 0);
		resJson.put("opUser", userID);
		resJson.put("workDiary", workDiary.toJSONObject());
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData obtainWorkDiary(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject msgJson = revData.getRevDataMsgJson();
		JSONObject resJson = new JSONObject();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Team_Manager) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}		
		int teamID = msgJson.getIntValue("teamID");
    	String strtoday = msgJson.getString("workDay");		
    	TeamWorkDiaryModel workDiary = TeamWorkDiaryDb.selectTeamWorkDiary(teamID, strtoday);
		if (workDiary != null) {
			resJson.put("workDiary", workDiary.toJSONObject());
		}
		
		resJson.put("resCode", 0);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	
}
